import 'package:enterprise_v6_app/app/components/custom_app_bar.dart';
import 'package:enterprise_v6_app/app/components/custom_modele/custom_card.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/ext/ext.dart';
import 'package:enterprise_v6_app/app/core/utils/file_util.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/emergency/emergency_res_expert_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/emergency/emergency_res_goods_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/emergency/emergency_res_nearby_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/emergency/emergency_res_target_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/emergency/emergency_res_team_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/emergency/emergency_team_member_entity.dart';
import 'package:enterprise_v6_app/app/modules/application/emergency/resource/detail/detail_ctrl.dart';
import 'package:enterprise_v6_app/app/modules/application/emergency/resource/detail/model.dart';

/// 应急资源详情
class EmergencyResourceDetailPage extends StatelessWidget {
  EmergencyResourceDetailPage({super.key});

  final controller = Get.put(EmergencyResourceDetailController());

  @override
  Widget build(BuildContext context) {
    return GetBuilder(
      init: controller,
      builder: (_) {
        return DefaultTabController(
          length: controller.tabs.length,
          child: Scaffold(
            appBar: CustomAppBar(
              titleText: controller.type?.toChinese,
              bottom: TabBar(
                enableFeedback: false,
                tabs: controller.tabs,
                onTap: (value) => controller.tabIdx = value,
                tabAlignment: TabAlignment.center,
                dividerColor: Colors.transparent,
                labelPadding: EdgeInsets.only(bottom: 10.w, left: 13.w, right: 13.w),
                labelStyle: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w500,
                ),
                unselectedLabelStyle: TextStyle(
                  fontSize: 16.sp,
                  fontWeight: FontWeight.w500,
                ),
                labelColor: Colors.black,
                unselectedLabelColor: const Color(0xffA0A7B5),
                indicatorPadding: EdgeInsets.only(top: 36.w, bottom: 10.w),
                indicator: const BoxDecoration(
                  image: DecorationImage(
                    image: AssetImage(
                      AppImages.icon_app_work_plan,
                    ),
                  ),
                ),
              ),
            ),
            body: Container(
              alignment: Alignment.topLeft,
              color: const Color(0xffF5F5F6),
              child: Padding(
                padding: EdgeInsets.only(top: 16.w),
                child: _buildBody(),
              ),
            ),
          ),
        );
      },
    );
  }

  Widget _buildBody() {
    switch (controller.tab) {
      case EmergencyResourceDetailPageType.basicInfo:
        return Container(
          decoration: const BoxDecoration(
            border: Border(top: BorderSide(color: Colors.blue, width: 2)),
            color: Colors.white,
          ),
          child: ListView(
            children: [
              AppGaps.vGap20,
              _buildBasicInfo(),
              AppGaps.vGap10,
              _buildResourceInfo(),
            ],
          ),
        );
      case EmergencyResourceDetailPageType.assessmentRecord:
        return _buildAssessmentRecord();
      case EmergencyResourceDetailPageType.memberInfo:
        return _buildMemberInfo();
    }
    return const SizedBox();
  }

  Widget _buildMemberInfo() {
    return ListView(
      padding: EdgeInsets.symmetric(vertical: 3.w, horizontal: 17.w),
      children: controller.members.map(_buildMemberItem).toList(),
    );
  }

  Widget _buildMemberItem(EmergencyTeamMemberEntity info) {
    return CustomCard(
      color: const Color(0x1A5C6DFF),
      titleWidget: Align(
        alignment: Alignment.centerLeft,
        child: Text(
          info.teamMemberName ?? '未知',
          style: TextStyle(
            fontSize: 16.w,
            fontWeight: FontWeight.w500,
            color: Colors.blue,
          ),
          textAlign: TextAlign.left,
        ),
      ).paddingSymmetric(horizontal: 12.w),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _buildEpuipInfoItemDetail('擅长专业：', info.beGoodAtMajor ?? ''),
          _buildEpuipInfoItemDetail('从业时间：', info.practiceLong ?? ''),
          _buildEpuipInfoItemDetail('年龄：', info.teamMemberAge?.toString() ?? ''),
          _buildEpuipInfoItemDetail('电话：', info.teamMemberPhone ?? ''),
          _buildEpuipInfoItemDetail('技术职称：', info.technology ?? ''),
        ],
      ),
    ).paddingOnly(bottom: 17.w);
  }

  /// 基础信息
  Widget _buildBasicInfo() {
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildInfoTop('${controller.type?.toChinese}信息'),
        AppGaps.vGap10,
        ..._buildBasicInfoItems(),
      ],
    );
  }

  Widget _buildInfoTop(String key) {
    return Row(
      mainAxisSize: MainAxisSize.min,
      children: [
        AppGaps.hGap24,
        CustomCard.leadingSmall,
        AppGaps.hGap10,
        Text(key, style: TextStyle(fontSize: 14.w, color: const Color(0xFF262F38))),
      ],
    );
  }

  List<Widget> _buildBasicInfoItems() {
    switch (controller.type) {
      case EmergencyResourceDetailPageType.expert:
        final data = controller.data as EmergencyResExpertEntity?;
        return [
          _buildBasicInfoItem('专家姓名', data?.expertName, true),
          _buildBasicInfoItem('性别', '男', true),
          _buildBasicInfoItem('出生日期', data?.dateOfBirth, true),
          _buildBasicInfoItem('学历', data?.educationalBackgroundName, true),
          _buildBasicInfoItem('专业', data?.major, true),
          _buildBasicInfoItem('职称', data?.professionalTitle, true),
          _buildBasicInfoItem('所属单位', data?.affiliatedUnit, true),
          _buildBasicInfoItem('联系方式', data?.contactInformation, true),
          _buildBasicInfoItem('电子邮箱', data?.email, true),
          _buildBasicInfoItem('到期时间', data?.expirationTime, true),
          _buildBasicInfoItem('工作经验', data?.workExperience, true),
          _buildBasicInfoItem('技能与专长', data?.skillsAndExpertise, true),
          _buildBasicInfoItem('专家照片', data?.expertPhotos, false, isPic: true),
          _buildBasicInfoItem('学历证书', data?.educationCertificate, false, isPic: true),
          _buildBasicInfoItem('专业资质证书', data?.professionalQualificationCertificate, false, isPic: true),
          _buildBasicInfoItem('协议（附件）', data?.annexToTheaAgreement, false, isFile: true),
        ];
      case EmergencyResourceDetailPageType.goods:
        final data = controller.data as EmergencyResGoodsEntity?;
        return [
          _buildBasicInfoItem('物质点名称', data?.nameOfMaterialPoint, true),
          _buildBasicInfoItem('所在区域位置', data?.locationOfTheRegion, true),
          _buildBasicInfoItem('地点', data?.place, true),
          _buildBasicInfoItem('负责人', data?.responsiblePerson, true),
          _buildBasicInfoItem('联系电话', data?.contactNumber, true),
        ];
      case EmergencyResourceDetailPageType.nearby:
        final data = controller.data as EmergencyResNearbyEntity?;
        return [
          _buildBasicInfoItem('资源机构名称', data?.resourceOrganizationName, true),
          _buildBasicInfoItem('机构类型', data?.institutionTypeName, true),
          _buildBasicInfoItem('负责人', data?.responsiblePerson, true),
          _buildBasicInfoItem('联系方式', data?.contactInformation, true),
          _buildBasicInfoItem('地址', data?.address, true),
          _buildBasicInfoItem('备注', data?.remarks, true),
          _buildBasicInfoItem('避难场所照片', data?.photosOfShelters, true, isPic: true),
          _buildBasicInfoItem('附件', data?.attachmentAddress, true, isFile: true),
        ];
      case EmergencyResourceDetailPageType.team:
        final data = controller.data as EmergencyResTeamEntity?;
        return [
          _buildBasicInfoItem('队伍名称', data?.teamName, true),
          _buildBasicInfoItem('队伍分类', data?.teamClassificationName, true),
          _buildBasicInfoItem('所属单位', data?.affiliatedUnit, true),
          _buildBasicInfoItem('负责人', data?.responsiblePerson, true),
          _buildBasicInfoItem('联系方式', data?.contactInformation, true),
          _buildBasicInfoItem('成立时间', data?.establishmentTime, true),
          _buildBasicInfoItem('地址', data?.address, true),
          _buildBasicInfoItem('合作期限', data?.periodOfCooperation, true),
          _buildBasicInfoItem('总人数', data?.totalNumberOfPeople.toString(), true),
          _buildBasicInfoItem('协议', data?.annexToTheAgreement, false, isFile: true),
          _buildBasicInfoItem('资质', data?.materialAttachments, false, isFile: true),
        ];
      case EmergencyResourceDetailPageType.target:
        final data = controller.data as EmergencyResTargetEntity?;
        return [
          _buildBasicInfoItem('敏感目标名称', data?.sensitiveTargetName, true),
          _buildBasicInfoItem('目标类型', data?.targetTypeName, true),
          _buildBasicInfoItem('重要性级别', data?.importanceLevelName, true),
          _buildBasicInfoItem('负责人', data?.responsiblePerson, true),
          _buildBasicInfoItem('联系方式', data?.contactInformation, true),
          _buildBasicInfoItem('场所地址', data?.placeAddress, true),
          _buildBasicInfoItem('安全措施', data?.safetyMeasures, true),
          _buildBasicInfoItem('敏感目标照片', data?.sensitiveTargetPhotos, true, isPic: true),
          _buildBasicInfoItem('附件', data?.attachmentAddress, true, isFile: true),
        ];
      default:
        break;
    }
    return [];
  }

  /// 基础信息 每一项
  Widget _buildBasicInfoItem(
    String key,
    String? val,
    bool isRequired, {
    bool isPic = false,
    bool isFile = false,
  }) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 7.w),
      child: Row(
        children: [
          SizedBox(
            width: 107.w,
            child: Row(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                if (isRequired)
                  Text(
                    '*',
                    style: TextStyle(
                      fontSize: 13.sp,
                      color: Colors.red,
                    ),
                    textAlign: TextAlign.center,
                  ),
                Text(
                  key,
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: const Color(0xFF7C7D93),
                  ),
                )
              ],
            ),
          ),
          val != null
              ? isPic
                  ? Row(
                      mainAxisSize: MainAxisSize.min,
                      children: val
                          .split(',')
                          .map((e) => SizedBox(
                                height: 77.w,
                                width: 77.w,
                                child: Image.network(Interface.fileUrl + e),
                              ).clickOnce(() {
                                FileUtils.openFile(Interface.fileUrl + e);
                              }))
                          .toList(),
                    )
                  : Text(
                      val.split('/').lastOrNull ?? '无',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: isFile ? Colors.blue : const Color(0xFF495061),
                      ),
                    ).clickOnce(() {
                      if (isFile) FileUtils.openFile(Interface.fileUrl + val);
                    })
              : Text(
                  '无',
                  style: TextStyle(
                    fontSize: 12.sp,
                    color: const Color(0xFF495061),
                  ),
                ),
        ],
      ),
    );
  }

  /// 评估记录
  Widget _buildAssessmentRecord() {
    final children = <Widget>[];
    for (int idx = 0; idx < controller.assessList.length; idx++) {
      final e = controller.assessList[idx];
      children.add(_buildAssessmentRecordItem(
        e.assessors,
        e.assessmentReport,
        e.assessmentReport.split('/').last,
        e.evaluationResults,
        e.updateDate,
        e.evaluationResults,
        idx,
      ));
    }
    return ListView(
      padding: EdgeInsets.symmetric(vertical: 13.w, horizontal: 17.w),
      children: children,
    );
  }

  /// 评估记录 每一项
  Widget _buildAssessmentRecordItem(
    String person,
    String reportUrl,
    String reportName,
    String type,
    String date,
    String result,
    int idx,
  ) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Row(
          children: [
            CustomCard.leadingSmall,
            AppGaps.hGap10,
            Text(
              '第${(idx + 1).toChinese}次评估',
              style: TextStyle(fontSize: 16.w, fontWeight: FontWeight.w500),
            ),
            AppGaps.hGap16,
            Text(
              date.split(' ').firstOrNull ?? '未知',
              style: TextStyle(
                fontSize: 12.w,
                fontWeight: FontWeight.w500,
                color: const Color.fromARGB(176, 73, 80, 97),
              ),
            ),
          ],
        ).paddingSymmetric(horizontal: 13.w),
        AppGaps.vGap10,
        Container(
          margin: EdgeInsets.only(left: 36.w),
          decoration: BoxDecoration(
            color: const Color(0x33587DF5),
            border: Border.all(color: const Color(0x33587DF5), width: 1),
            borderRadius: BorderRadius.circular(4.w),
          ),
          child: Column(
            children: [
              _buildAssessmentRecordItemDetail('评估结果：', result),
              _buildAssessmentRecordItemDetail('评估人员：', person),
              _buildAssessmentRecordItemDetail(
                '评估报告：',
                reportName,
                url: reportUrl,
              ),
            ],
          ),
        ),
        AppGaps.vGap20,
      ],
    );
  }

  Widget _buildAssessmentRecordItemDetail(String key, String val, {String? url}) {
    final valWidget = Text(
      val,
      style: TextStyle(
        fontSize: 12.w,
        color: url == null ? const Color(0xFF495061) : Colors.blue,
      ),
    );
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 7.w, horizontal: 13.w),
      child: Row(
        children: [
          Text(
            key,
            style: TextStyle(fontSize: 13.w, color: const Color(0xFFA0A7B5)),
          ),
          AppGaps.hGap6,
          url == null
              ? valWidget
              : InkWell(
                  onTap: () => FileUtils.openFile(url),
                  child: valWidget,
                )
        ],
      ),
    );
  }

  /// 资源列表
  Widget _buildResourceInfo() {
    if (!controller.displayInfo) return const SizedBox();
    final children = controller.infos.map(
      (info) => CustomCard(
        color: const Color(0x1A5C6DFF),
        titleWidget: Align(
          alignment: Alignment.centerLeft,
          child: Text(
            info.$1,
            style: TextStyle(
              fontSize: 16.w,
              fontWeight: FontWeight.w500,
              color: Colors.blue,
            ),
            textAlign: TextAlign.left,
          ),
        ).paddingSymmetric(horizontal: 12.w),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildEpuipInfoItemDetail('分类：', info.$2),
            _buildEpuipInfoItemDetail('数量：', info.$3),
            _buildEpuipInfoItemDetail('用途：', info.$4),
            _buildEpuipInfoItemDetail('储存运输要求：', info.$5),
            _buildEpuipInfoItemDetail('图片：', '', picUrls: info.$6),
          ],
        ),
      ).paddingAll(16.w),
    );
    if (children.isEmpty) return const SizedBox();
    return Column(
      mainAxisSize: MainAxisSize.min,
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        _buildInfoTop('${controller.type?.toChinese}明细'),
        ...children,
      ],
    );
  }

  Widget _buildEpuipInfoItemDetail(String key, String val, {List<String>? picUrls}) {
    final valWidget = Text(
      val,
      style: TextStyle(
        fontSize: 12.w,
        color: const Color(0xFF495061),
      ),
    );
    picUrls?.removeWhere(
      (element) => element.isBlankString,
    );
    picUrls = picUrls?.map((e) => Interface.fileUrl + e).toList();
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 7.w, horizontal: 13.w),
      child: Row(
        children: [
          SizedBox(
            width: 99.w,
            child: Text(
              key,
              style: TextStyle(fontSize: 13.w, color: const Color(0xFFA0A7B5)),
            ),
          ),
          AppGaps.hGap6,
          if (picUrls == null)
            valWidget
          else
            SizedBox(
              height: 77.w,
              width: 183.w,
              child: ListView(
                scrollDirection: Axis.horizontal,
                children: picUrls
                    .map(
                      (e) => Container(
                        decoration: BoxDecoration(
                          color: Colors.blue[100],
                          borderRadius: BorderRadius.circular(
                            7.w,
                          ),
                        ),
                        margin: const EdgeInsets.all(3),
                        child: Image.network(e),
                      ).clickOnce(() => FileUtils.openFile(e)),
                    )
                    .toList(),
              ),
            )
        ],
      ),
    );
  }
}
